import 'package:flutter/material.dart';
import 'package:ad_suyi_flutter_sdk/ad_suyi_ad.dart';

import 'key.dart';

class RewardPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _RewardState();
}

class _RewardState extends State<RewardPage> {
  ADSuyiRewardAd? _rewardAd;

  @override
  Widget build(BuildContext context) {
    // showRewardAd();
    return Scaffold(
      appBar: AppBar(
        title: Text("Reward"),
      ),
      body: Center(
        child: GestureDetector(
            onTap: () {
              showRewardAd();
            },
            child: Container(
              height: 70,
              margin: EdgeInsets.all(50),
              child: Text("获取并且展示"),
            )),
      ),
    );
  }

  showRewardAd() {
    if (_rewardAd != null) {
      return;
    }
    _rewardAd = ADSuyiRewardAd(posId: KeyManager.rewardPosid());
    // 激励视频加载失败回调
    _rewardAd!.onFailed = (AdErrorInfo adErrorInfo) {
      print("激励视频广告加载失败 errorCode : " +
          adErrorInfo.errorCode.toString() +
          " errorDescription : " +
          adErrorInfo.errorDescription);
      releaseRewardAd();
    };
    // 激励视频曝光回调
    _rewardAd!.onExposed = (AdInfo adInfo) {
      print("激励视频广告曝光了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
    };
    // 激励视频加载成功回调
    _rewardAd!.onSucced = (AdInfo adInfo) {
      print("激励视频广告成功了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
      playRewardAd();
    };
    // 激励视频点击回调
    _rewardAd!.onClicked = (AdInfo adInfo) {
      print("激励视频广告点击了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
    };
    // 激励视频达到激励条件回调
    _rewardAd!.onRewarded = (AdInfo adInfo) {
      print("激励视频广告激励达成 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
    };
    // 激励视频关闭回调
    _rewardAd!.onClosed = (AdInfo adInfo) {
      print("激励视频广告关闭 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
      releaseRewardAd();
    };
    // 加载激励视频
    _rewardAd!.load();
  }

  void releaseRewardAd() {
    _rewardAd?.release();
    _rewardAd = null;
  }

  void playRewardAd() {
    // 展示激励视频
    _rewardAd!.show();
  }

  @override
  void dispose() {
    releaseRewardAd();
    super.dispose();
  }
}
